package cz.anime.ppro.beans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cz.anime.ppro.logic.FragmentComponent;
import cz.anime.ppro.logic.UserComponent;
import cz.anime.ppro.model.Fragment;
import cz.anime.ppro.model.Webuser;

@Component
@ManagedBean
@Scope("view")
public class UserFragmentAdministrationBean {

	private List<Fragment> userFragments;
	private List<Fragment> otherFragments;
	
	@Autowired
	private UserComponent userComponent;
	
	@Autowired
	private FragmentComponent fragmentComponent;

	@PostConstruct
	public void init(){
		List<Fragment> fragments = fragmentComponent.getFragements();
		userFragments = new ArrayList<Fragment>();
		otherFragments = new ArrayList<Fragment>();
		for (Fragment fragment : fragments) {
			boolean notAdded = true;
				for (Webuser user : fragment.getWebusers()) {
					if (user.getId() != 0 && user.getId() == getUser()) {
						userFragments.add(fragment); 
						notAdded = false;
					}
				}
			if (notAdded) {
				otherFragments.add(fragment);
			}
		}
	}
	
	public String addFragment(int fragmentId){
		Webuser webuser = userComponent.getUser(getUser());
		Fragment fragment = fragmentComponent.getFragment(fragmentId);
		
		fragment.getWebusers().add(webuser);
		fragmentComponent.save(fragment);
		
		return "admin-my-fragments?faces-redirect=true";
	}
	
	public String removeFragment(int fragmentId){
		Webuser webuser = userComponent.getUser(getUser());
		Fragment fragment = fragmentComponent.getFragment(fragmentId);
		
		fragment.getWebusers().remove(webuser);
		fragmentComponent.save(fragment);
		
		return "admin-my-fragments?faces-redirect=true";
	}
	
	private int getUser(){
		return userComponent.getUserByNick(userComponent.getCurrentUsernameFromSession()).getId();
	}

	public List<Fragment> getUserFragments() {
		return userFragments;
	}

	public void setUserFragments(List<Fragment> userFragments) {
		this.userFragments = userFragments;
	}

	public List<Fragment> getOtherFragments() {
		return otherFragments;
	}

	public void setOtherFragments(List<Fragment> otherFragments) {
		this.otherFragments = otherFragments;
	}
	
}
